package com.mew.common.dc.db;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.dc.mapper.CustomerMapper;
import com.mew.common.dc.mapper.UserMapper;
import com.mew.common.enm.DataStateType;
import com.mew.common.enm.UserLoginType;
import com.mew.common.entity.user.Customer;
import com.mew.common.entity.user.User;
import com.mew.common.exception.MewException;
import com.mew.common.exception.ResponseCode;
import com.mew.common.util.GenderType;
import com.mew.common.util.MD5Encrypt;
import com.mew.common.util.RandomIdUtil;
import com.mew.common.vo.web.CustomerVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public User createUser(User user, int gidStart, int gidLen){
        user.setId(RandomIdUtil.getUserId());
        user.setGid(RandomIdUtil.getGid(gidStart, gidLen));

        if (StringUtils.isNotEmpty(user.getPassword())){
            String password = MD5Encrypt.MD5(user.getPassword());
            user.setPassword(password);
        }
        user.setSex(GenderType.Female.code());
        user.setNickname("Player-"+user.getGid());
        insertUser(user, gidStart, gidLen, 0);
        //--------------------
        user.setState(1);
        user.setHeadPath(0);
        user.setSex(0);
        user.setGuideType(0);
        redisTemplate.opsForHash().put(RedisConstantValue.USER_INFO, user.getId(), user);
        return user;
    }

    private User insertUser(User user, int gidStart, int gidLength, int checkLoop)throws MewException {
        if (checkLoop > 10){
            log.error("User insert gid Repeat gt 10 times {}", user.toString());
            throw new MewException("User insert gid Repeat gt 10 times");
        }

        try {
             userMapper.insert(user);
        }catch (Exception e){
            log.error("User insert gid Repeat gt {} times gid {} userId {}", checkLoop, user.getGid(), user.getId());
            user.setId(RandomIdUtil.getUserId());
            user.setGid(RandomIdUtil.getGid(gidStart, gidLength)); //游戏号
            return insertUser(user, gidStart, gidLength, checkLoop+1);
        }
        return user;
    }

    /**
     * @param userId
     * @param tel
     * @return  0 表示不重复 1 重复
     */
    public int checkTel(long userId, String tel){
        if (StringUtils.isEmpty(tel)){
            return 0;
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().select(User::getId, User::getTelNumber).eq(User::getTelNumber, tel));
        if (null == user || null == user.getId()){
            return 0;
        }
        return  userId < 1 ? 1 : userId == user.getId() ? 0 : 1;

    }


    public User getRedisUserById(long userId){
        if (userId < 1){
            return null;
        }
        User user =  (User) redisTemplate.opsForHash().get(RedisConstantValue.USER_INFO, userId);
        if(null == user){
            user = userMapper.selectById(userId);
            if (null == user || user.getState() != DataStateType.Active.code()){
                return null;
            }
            redisTemplate.opsForHash().put(RedisConstantValue.USER_INFO, userId, user);
        }
        return user;
    }

    public User getUserById(long userId){
        if (userId < 1){
            return null;
        }

        User user = userMapper.selectById(userId);
        if (null == user || user.getState() != DataStateType.Active.code()){
            return null;
        }
        redisTemplate.opsForHash().put(RedisConstantValue.USER_INFO, userId, user);

        return user;
    }

    public User getDbUserById(long userId){
        if (userId < 1){
            return null;
        }

        return userMapper.selectById(userId);
    }

    public User getUserByLoginType(String acc, UserLoginType loginType)throws MewException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>().eq(User::getState, 1);
        switch (loginType){
            case Tel: queryWrapper = queryWrapper.eq(User::getTelNumber, acc); break;
            case MAC: queryWrapper = queryWrapper.eq(User::getAddMac, acc); break;
        }
        List<User> list = userMapper.selectList(queryWrapper);
        if (null == list || list.isEmpty()){
            return null;
        }
        if (list.size() > 1){
            log.error("UserRepeat：{} {}", acc, loginType);
            throw new MewException(ResponseCode.UserRepeat);
        }

        User user = list.get(0);
        redisTemplate.opsForHash().put(RedisConstantValue.USER_INFO, user.getId(), user);
        return user;
    }


    public void deleteByUserId(long userId){
        redisTemplate.opsForHash().delete(RedisConstantValue.USER_INFO, userId);
    }

    public User getUserByGid(String gid){
        if (StringUtils.isEmpty(gid)){
            return null;
        }

        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getGid, gid).eq(User::getState,1);
        User user = null;
        try {
            user = userMapper.selectOne(eq);
        } catch (Exception e) {
            log.debug("用户重复：{}",gid);
            e.printStackTrace();
            return null;
        }

        return user;
    }

    public User getAllUserByGid(String gid){
        if (StringUtils.isEmpty(gid)){
            return null;
        }
        gid = gid.replace(" ","");
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getGid, gid);
        User user = null;
        try {
            user = userMapper.selectOne(eq);
        } catch (Exception e) {
            log.debug("用户重复：{}",gid);
            e.printStackTrace();
            return null;
        }

        return user;
    }

    public void updateUser(User user, User other){
        userMapper.updateById(other);
        redisTemplate.opsForHash().put(RedisConstantValue.USER_INFO, user.getId(), user);
    }

    /**
     * 加载客服列表
     */
    public void loadCustomer(){
        List<Customer> customerList = customerMapper.selectList(new LambdaQueryWrapper<Customer>().eq(Customer::getStatus, 0));
        for (Customer customer : customerList) {
            User cu = getRedisUserById(customer.getCustomerId());
            CustomerVo customerVo = CustomerVo.builder()
                    .uid(customer.getCustomerId())
                    .gid(cu.getGid())
                    .email(customer.getEmail())
                    .line(customer.getLine()).build();
            redisTemplate.opsForHash().put(RedisConstantValue.USER_CUSTOMER,customer.getCustomerId(),customerVo);
        }
    }

}
